package com.p2p.system.controller;


import com.p2p.model.entity.Employee;
import com.p2p.model.entity.Logininfo;
import com.p2p.model.vo.LoginVo;
import com.p2p.system.common.Result;
import com.p2p.system.entity.Iplog;
import com.p2p.system.entity.Userinfo;
import com.p2p.system.exception.MyCustomerException;
import com.p2p.system.service.EmployeeService;
import com.p2p.system.service.IplogService;
import com.p2p.system.service.LogininfoService;
import com.p2p.system.service.UserinfoService;
import com.p2p.system.util.IpUtil;
import com.p2p.system.util.JwtHelper;
import com.p2p.system.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.velocity.runtime.directive.MacroParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 罗永东
 * @since 2023-12-07
 */

@CrossOrigin
@RestController
@Api(tags = "p2p项目登录模块")
@RequestMapping("/system/login")
public class LogininfoController {

    @Autowired
    private EmployeeService employeeService;


    @Autowired
    private IplogService iplogService;


    @Autowired
    private LogininfoService logService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@RequestBody LoginVo login, HttpServletRequest request) {
        System.out.println("123132132123132123321*****************:"+login.getPhone());

        Logininfo loginInfo = logService.getUserByPhone(login.getPhone());

        Iplog iplog = new Iplog();
        iplog.setLogininfoid(loginInfo.getId());
        iplog.setUsername(loginInfo.getPhone());
        iplog.setIp(IpUtil.getIpAddress(request));
        // 设置时间为当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(currentDateTime);
        iplog.setLogintime(timestamp.toLocalDateTime());


        if (loginInfo == null) {
            iplog.setLoginstate(1);

            throw new MyCustomerException(201,"账号不存在");
        }
        System.out.println(loginInfo.toString());
        String password = login.getPassword();
        if (!password.equals(loginInfo.getPassword())) {
            iplog.setLoginstate(1);
            throw new MyCustomerException(201,"密码错误");
        }
        if (loginInfo.getState().intValue()==0) {
            iplog.setLoginstate(1);
            throw new MyCustomerException(201, "账号已停用");
        }
        iplog.setLoginstate(1);
        iplog.setLogintype(1);
        iplogService.save(iplog);

        String token = JwtHelper.createToken(loginInfo.getId().toString(), null, loginInfo.getPhone());

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);

        return Result.ok(token);
    }


    /**
     *  后端登录接口
     * @return
     */
    @ApiOperation("后台登录")
    @PostMapping(value = "/syslogin")
    public Result sysLogin(@RequestBody LoginVo loginVo)
    {

        System.out.println(loginVo.getPhone());

        Employee loginInfo = employeeService.getUserByPhone(loginVo.getPhone());
        if (loginInfo == null) {
            throw new MyCustomerException(201,"账号不存在");
        }
        System.out.println(loginInfo.toString());
        String password = loginVo.getPassword();
        if (!password.equals(loginInfo.getEmppassword())) {
            throw new MyCustomerException(201,"密码错误");
        }




        String token = JwtHelper.createToken(loginInfo.getId().toString(), null, loginInfo.getEmpphone());

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);

        return Result.ok(token);
    }
    /**
     *  获取用户信息
     */
    @ApiOperation("获取登录信息")
    @GetMapping(value = "/info")
    public Result info()
    {
        Map<String,Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("introduction","I am a super admin");
        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name","admin hello!");
        return Result.ok(map);

    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation("退出登录")
    @PostMapping(value = "/logout")
    public Result logout(){
        return Result.ok();
    }


    @ApiOperation("手机号注册")
    @PostMapping("/register")
    public Result register(@RequestBody Logininfo login){

        Logininfo userByPhone = logService.getUserByPhone(login.getPhone());
        if (userByPhone != null) {
            throw new MyCustomerException(201, "改手机号已存在");
        }

        boolean save = this.logService.save(login);
        if (save) {
            return Result.ok("注册成功").code(200).message("注册成功");
        }

        return Result.fail().code(219).message("注册失败");

    }


    @ApiOperation("注销用户信息")
    @GetMapping("/signOut/{id}")
    public Result signOtu(@PathVariable Long id){

        boolean b = this.logService.removeById(id);
        if (b) {
            return Result.ok();
        }

        return Result.fail();
    }

    @ApiOperation("根据id修改用户密码")
    @PostMapping("updatePassword")
    public Result updatePassword(@RequestBody Logininfo logininfo){

        Logininfo logininfoOld = logService.getById(logininfo.getId());

        Logininfo logininfoNew = new Logininfo();
        logininfoNew.setPhone(logininfoOld.getPhone());
        logininfoNew.setState(logininfoOld.getState());
        logininfoNew.setIsDeleted(logininfoOld.getIsDeleted());

        logininfoNew.setId(logininfo.getId());
        logininfoNew.setPassword(logininfo.getPassword());

        boolean b = logService.updateById(logininfoNew);
        if (b){
           return Result.ok();
        }else {
           return Result.fail();
        }
    }

    @ApiOperation("根据id获取用户密码")
    @PostMapping("/getPasswordById/{id}")
    public Result updatePassword(@PathVariable Long id){
        String oldPassword = logService.getPasswordById(id);
        return Result.ok(oldPassword);
    }


}
